package com.happyscan138.makefun.Fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.happyscan138.makefun.BaseAdapter.Persional_question;
import com.happyscan138.makefun.R;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.adapter.Persional_questionAdapter;
import com.happyscan138.makefun.base.LoadListView;
import com.happyscan138.makefun.base.WaitNetDataPop;
import com.happyscan138.makefun.questionDetailed;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static android.content.Context.MODE_PRIVATE;
import static com.happyscan138.makefun.Urls.Urls.base;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2017/1/1.
 */

public class persional_questuion extends Fragment implements LoadListView.IloadListener {
    private Context mContext;
    private List<Persional_question> listData;
    private LoadListView persional_question;
    private SharedPreferences preferences;
    private String access_key;
    private Intent intent;
    private Persional_question data;
    private int  PROBLEM_ID_INDEX ;
    private String jsonStr;
    private SwipeRefreshLayout mSwipeLayout;
    private Handler handler;
    private WaitNetDataPop waitNetDataPop=new WaitNetDataPop(getActivity());
    private Persional_questionAdapter adapter;
    private ArrayList<Integer> ID;
    //Tab用来标记集合第一个元素，是否发生变化，用来做下拉刷新
    private int Tab;
    private int IfRefresh;
    private String userID;
    private String PersionalUserID;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.persional_question,null);
        userID=getArguments().getString("user_id");
        log.e("bundle",userID);
        waitNetDataPop=new WaitNetDataPop(getActivity());
        waitNetDataPop.displayPop();
        mContext = getActivity();
        client=new AsyncHttpClient();
        params=new RequestParams();
        ID=new ArrayList<Integer>();
        preferences = getActivity().getSharedPreferences("UserInfo", MODE_PRIVATE);
        access_key=preferences.getString("UserId","");
        initView(view);
        getAdapterView();
        persional_question.setInterface(this);
        return view;
    }
    public void initView(View view){
        persional_question=(LoadListView)view.findViewById(R.id.persional_listview);
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.persional_swipe);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                params.put("page_count", "10");
                params.put("problem_id_index", 0);
                params.put("access_key",access_key);
                params.put("user_id",userID);

                RequestHandle handle = client.post(Urls.QuestionPer, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            JSONObject obj=jsonArray.getJSONObject(0);
                            IfRefresh=obj.getInt("problem_id");
                            log.e("IfRefresh",IfRefresh+"");
                            log.e("IfRefresh",Tab+"");
                            if (IfRefresh == Tab) {
                                Toast.makeText(getActivity(), "已是最新数据", Toast.LENGTH_SHORT).show();
                            }    else {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject objectData = jsonArray.getJSONObject(i);
                                    PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                    ID.add(PROBLEM_ID_INDEX);
                                    data=new Persional_question();
                                    PersionalUserID = objectData.getString("user_id");
                                    log.e("user_id", data.userID + "");
                                    data.icon = Urls.base + objectData.getString("img_path");
                                    log.e("icon", data.icon.toString());
                                    data.name = objectData.getString("nick_name");
                                    data.time = objectData.getString("create_date");
                                    data.text = objectData.getString("content");
                                    data.resource = Urls.base + objectData.getString("resource");
                                    data.Thumb=base+objectData.getString("thumb");
                                    data.viewNum = objectData.getInt("read_count");
                                    data.answerNum = objectData.getInt("replay_count");
                                    data.commentNum = i;
                                    data.goodNum = objectData.getInt("admire_count");
                                    data.problem_id = objectData.getString("problem_id");
                                    listData.add(data);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                mSwipeLayout.setRefreshing(false);
            }
        });
    }
    private void getAdapterView() {
        params.put("page_count", "10");
        params.put("problem_id_index", 0);
        params.put("access_key",access_key);
        params.put("user_id",userID);
        log.e("params", params.toString());
        RequestHandle handle=client.post(Urls.QuestionPer,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                waitNetDataPop.dismiss();
                jsonStr = response.toString();
                log.e("jsonStr", jsonStr);
                listData = new ArrayList<>();
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject objectData = jsonArray.getJSONObject(i);
                        PROBLEM_ID_INDEX = objectData.getInt("problem_id");
                        ID.add(PROBLEM_ID_INDEX);
                        log.e("ID",ID.toString());
                        Tab=ID.get(0);
                        data = new Persional_question();
                        data.userID = objectData.getString("user_id");
                        log.e("user_id", data.userID + "");
                        data.icon = base + objectData.getString("img_path");
                        log.e("icon", data.icon.toString());
                        data.name = objectData.getString("nick_name");
                        data.time = objectData.getString("create_date");
                        data.text = objectData.getString("content");
                        data.resource = base + objectData.getString("resource");
                        data.Thumb=base+objectData.getString("thumb");
                        data.viewNum = objectData.getInt("read_count");
                        data.answerNum = objectData.getInt("replay_count");
                        data.commentNum = i;
                        data.goodNum = objectData.getInt("admire_count");
                        data.problem_id = objectData.getString("problem_id");
                        listData.add(data);

                    }
                    log.e("listData", listData.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter = new Persional_questionAdapter(getActivity(), listData, access_key, persional_question);
                persional_question.setAdapter(adapter);
                persional_question.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        intent = new Intent();
                        data = listData.get(position);
                        intent.putExtra("problem_id", data.problem_id);
                        intent.setClass(getActivity(), questionDetailed.class);
                        startActivity(intent);
                    }
                });
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("responseString",responseString);
            }
        });

    }

    @Override
    public void onLoad() {
        handler = new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                params=new RequestParams();
                params.put("page_count", "10");
                params.put("problem_id_index", ID.get(ID.size()-1));
                log.e("last_item_index",ID.get(ID.size()-1)+"");
                params.put("access_key",access_key);
                params.put("user_id",userID);
                log.e("last_item_index",params.toString());
                RequestHandle handle=client.post(Urls.cteatQuestionHot,params,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        waitNetDataPop.dismiss();
                        jsonStr = response.toString();
                        log.e("jsonStr", jsonStr);
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject objectData = jsonArray.getJSONObject(i);
                                PROBLEM_ID_INDEX = objectData.getInt("problem_id");
                                ID.add(PROBLEM_ID_INDEX);
                                log.e("PROBLEM_ID_INDEX", PROBLEM_ID_INDEX + "");
                                data = new Persional_question();
                                data.userID = objectData.getString("user_id");
                                log.e("user_id", data.userID + "");
                                data.icon = base + objectData.getString("img_path");
                                log.e("icon", data.icon.toString());
                                data.name = objectData.getString("nick_name");
                                data.time = objectData.getString("create_date");
                                data.text = objectData.getString("content");
                                data.Thumb=base+objectData.getString("thumb");
                                data.resource = base + objectData.getString("resource");
                                data.viewNum = objectData.getInt("read_count");
                                data.answerNum = objectData.getInt("replay_count");
                                data.commentNum = i;
                                data.goodNum = objectData.getInt("admire_count");
                                data.problem_id = objectData.getString("problem_id");
                                listData.add(data);

                            }
                            log.e("listData", listData.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                persional_question.loadComplete();
            }
        },2000);
    }
}
